package com.itheima.health.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.OrderMP;
import com.itheima.health.pojo.SetmealMP;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderServiceMP;
import com.itheima.health.service.ReportService;
import com.itheima.health.service.SetmealServiceMP;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/report")
public class ReportController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private SetmealServiceMP setmealService;

    @Autowired
    private OrderServiceMP orderService;
    @Autowired
    private ReportService reportService;

    @GetMapping("/getMemberReport")
    public Result getMemberReport() {
        //定义返回的数据
        HashMap<String, Object> map = new HashMap<>();
        //定义月份列表
        ArrayList<String> months = new ArrayList<>();
        //定义会员数量
        ArrayList<Integer> memberCount = new ArrayList<>();
        //日期的格式
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM");
        Calendar calendar = Calendar.getInstance();
        //近两年内的数据
        calendar.add(Calendar.MONTH, -24);
        for (int i = 0; i < 24; i++) {
            //获取到格式化后的日期
            String month = format.format(calendar.getTime());
            months.add(month);
            //查询当前月份下注册的会员数量
            LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
            wrapper.between(Member::getRegTime, month + ".01", month + ".31");
            memberCount.add(memberService.count(wrapper));
            //月份自增
            calendar.add(Calendar.MONTH, 1);
        }
        //封装数据
        map.put("months", months);
        map.put("memberCount", memberCount);
        //返回结果
        if (map.get("memberCount") != null) {
            return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } else {
            return new Result(false, MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    @GetMapping("/getSetmealReport")
    public Result getSetmealReport() {
        //定义返回的数据
        HashMap<String, Object> map = new HashMap<>();
        //定义套餐列表
        ArrayList<String> setmealNames = new ArrayList<>();
        //定义套餐数量
        ArrayList<Map<String, Object>> setmealCount = new ArrayList<>();

        List<SetmealMP> setmeals = setmealService.list();
        for (SetmealMP setmeal : setmeals) {
            LambdaQueryWrapper<OrderMP> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderMP::getSetmealId, setmeal.getId());
            int count = orderService.count(wrapper);
            //只统计被购买过的套餐
            if (count > 0) {
                //套餐名称
                setmealNames.add(setmeal.getName());
                //套餐数量
                HashMap<String, Object> countMap = new HashMap<>();
                countMap.put("name", setmeal.getName());
                countMap.put("value", count);
                setmealCount.add(countMap);
            }
        }

        //封装数据
        map.put("setmealNames", setmealNames);
        map.put("setmealCount", setmealCount);
        //返回结果
        if (map.get("setmealNames") != null) {
            return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } else {
            return new Result(false, MessageConst.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() throws Exception {
        Map<String, Object> businessReportData = reportService.getBusinessReportData();
        return new Result(true, MessageConst.GET_BUSINESS_REPORT_SUCCESS, businessReportData);

    }

    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        Map<String, Object> businessReportData = reportService.getBusinessReportData();

        String reportDate = (String) businessReportData.get("reportDate");
        Integer todayNewMember = (Integer) businessReportData.get("todayNewMember");
        Integer totalMember = (Integer) businessReportData.get("totalMember");
        Integer thisWeekNewMember = (Integer) businessReportData.get("thisWeekNewMember");
        Integer thisMonthNewMember = (Integer) businessReportData.get("thisMonthNewMember");
        Integer todayOrderNumber = (Integer) businessReportData.get("todayOrderNumber");
        Integer todayVisitsNumber = (Integer) businessReportData.get("todayVisitsNumber");
        Integer thisWeekOrderNumber = (Integer) businessReportData.get("thisWeekOrderNumber");
        Integer thisWeekVisitsNumber = (Integer) businessReportData.get("thisWeekVisitsNumber");
        Integer thisMonthOrderNumber = (Integer) businessReportData.get("thisMonthOrderNumber");
        Integer thisMonthVisitsNumber = (Integer) businessReportData.get("thisMonthVisitsNumber");
        List<HashMap<String, Object>> hotSetmeals = (List<HashMap<String, Object>>) businessReportData.get("hotSetmeal");
        System.out.println(hotSetmeals.toString());
        System.out.println(reportDate);

        //获得Excel模板文件绝对路径
        String temlateRealPath = getClass().getResource("/template/report_template.xlsx").getPath();

        //读取模板文件创建Excel表格对象
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));
        XSSFSheet sheet = workbook.getSheetAt(0);
        XSSFRow row = sheet.getRow(2);
        row.getCell(5).setCellValue(reportDate);//日期

        row = sheet.getRow(4);
        row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
        row.getCell(7).setCellValue(totalMember);//总会员数

        row = sheet.getRow(5);
        row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
        row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

        row = sheet.getRow(7);
        row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
        row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

        row = sheet.getRow(8);
        row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
        row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

        row = sheet.getRow(9);
        row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
        row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

        int rowNum = 12;
        for (Map map : hotSetmeals) {//热门套餐
            String name = (String) map.get("name");
            Long setmeal_count = Long.valueOf(map.get("setmeal_count").toString());
            BigDecimal proportion = BigDecimal.valueOf(Double.valueOf(map.get("proportion").toString()));
            row = sheet.getRow(rowNum++);
            row.getCell(4).setCellValue(name);//套餐名称
            row.getCell(5).setCellValue(setmeal_count);//预约数量
            row.getCell(6).setCellValue(proportion.doubleValue());//占比
        }
        //通过输出流进行文件下载
        ServletOutputStream out = httpServletResponse.getOutputStream();
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setHeader("content-Disposition", "attachment;filename=report.xlsx");
        workbook.write(out);

        out.flush();
        out.close();
        workbook.close();

        return null;
    }
}
